package com.longrise.android.byjk.advertisement.detail;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import com.longrise.android.byjk.R;
import com.longrise.common.utils.NetUtil;
import com.longrise.common.utils.PrintLog;


/**
 * Created by callxkj on 2017/1/10.
 * 广告的详情页base页面
 */

public abstract class BaseAdDetailActivity extends Activity implements View.OnClickListener, View.OnKeyListener {

    private static final String TAG = "BaseAdDetailActivity";
    private RelativeLayout mRlback;
    private WebView mWv;
    private ProgressBar mPb;
    private Handler mHandler = new Handler();
    private RelativeLayout mRlload_error;
    private String mUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addetail);
        init(savedInstanceState);
        initView();
        initData();
        initEvent();
    }

    private void initView(){
        mRlback = (RelativeLayout) findViewById(R.id.addetail_back);
        mWv = (WebView) findViewById(R.id.addetail_webview);
        mPb = (ProgressBar) findViewById(R.id.addetail_pb);
        mRlload_error = (RelativeLayout) findViewById(R.id.loading_error_rootview);
    }

    private void initData(){
        WebSettings webSettings = mWv.getSettings();

        webSettings.setLoadWithOverviewMode(true);

        // 设置WebView属性，能够执行Javascript脚本
        webSettings.setJavaScriptEnabled(true);
        // 设置可以访问文件
        webSettings.setAllowFileAccess(true);

        //设置 缓存模式 不用缓存 使用localStorage
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setDomStorageEnabled(true);
        webSettings.setAppCacheMaxSize(1024 * 1024 * 8);
        String absolutePath = this.getApplicationContext().getCacheDir().getAbsolutePath();
        webSettings.setAppCachePath(absolutePath);
        webSettings.setAllowFileAccess(true);
        webSettings.setAppCacheEnabled(true);

        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);

        webSettings.setLoadsImagesAutomatically(true);

        String mUrl = getUrl();

        mWv.setWebViewClient(new BaseAdDetailClient());

        mWv.setWebChromeClient(new BaseAdDetailChromeClient());

        if (checkNetwork()) {
            // 加载需要显示的网页
            mWv.loadUrl(mUrl);
        }
    }

    private void initEvent(){
        mRlback.setOnClickListener(this);
        mWv.setOnKeyListener(this);
        mRlload_error.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.addetail_back:
                finish();
                break;
            case R.id.loading_error_rootview:
                reload();
                break;
        }
    }

    @Override
    public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mWv.canGoBack()) {
            if(checkNetwork()){
                mWv.goBack();
            }
            return true;
        }
        return false;
    }


    private class BaseAdDetailClient extends WebViewClient{

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            if(checkNetwork()){
                mWv.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            mUrl = url;
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if(checkNetwork()){
                view.loadUrl(url);
            }
            return true;

        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            loading_error();
        }
    }

    private class BaseAdDetailChromeClient extends WebChromeClient{

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            PrintLog.d(TAG,"newProgress:"+newProgress);
            mPb.setProgress(newProgress);
            if(newProgress==100){
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        dismissPb();
                    }
                },200);
            }
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (!TextUtils.isEmpty(title) && title.toLowerCase().contains("error")) {
                loading_error();
            }
        }
    }

    /**
     * 让progressbar消失
     */
    private void dismissPb(){
        mPb.setProgress(0);
    }



    /**
     * 检查是否有网络
     * @return
     */
    private boolean checkNetwork() {
        if (!NetUtil.checkNetEnable()) {
            loading_error();
            return false;
        } else {
            return true;
        }
    }

    /**
     * 重新加载
     */
    private void reload(){
        if(checkNetwork()){
            mRlload_error.setVisibility(View.GONE);
            mWv.setVisibility(View.VISIBLE);
            mWv.loadUrl(mUrl);
        }
    }

    /**
     * 加载失败后
     */
    private void loading_error(){
        mRlload_error.setVisibility(View.VISIBLE);
        mWv.setVisibility(View.GONE);
    }


    /**
     * 初始化
     */
    protected abstract void init(Bundle savedInstanceState);

    /**
     * 需要加载的地址
     * @return 请求地址
     */
    protected abstract String getUrl();


}
